package com.zh.harmony.intentservice;

import com.zh.harmony.handlerthread.HandlerThread;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.rpc.IRemoteObject;

/**
 * IntentService，其任务运行在子线程
 */
public abstract class IntentService extends Ability {
    private volatile EventRunner mServiceEventRunner;
    private volatile ServiceHandler mServiceHandler;
    private final String mName;

    /**
     * 子线程EventHandler
     */
    private final class ServiceHandler extends EventHandler {
        public ServiceHandler(EventRunner runner) throws IllegalArgumentException {
            super(runner);
        }

        @Override
        protected void processEvent(InnerEvent event) {
            super.processEvent(event);
            //收到事件，处理
            onHandleIntent((Intent) event.object);
            //处理完毕，销毁服务
            terminateAbility();
        }
    }

    /**
     * 构造方法，并指定内部的子线程的名称
     */
    public IntentService(String name) {
        super();
        mName = name;
    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        //启动子线程
        HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
        thread.start();
        //创建子线程的EventHandler
        mServiceEventRunner = thread.getEventRunner();
        mServiceHandler = new ServiceHandler(mServiceEventRunner);
    }

    @Override
    protected void onCommand(Intent intent, boolean restart, int startId) {
        super.onCommand(intent, restart, startId);
        //发送事件，通知需要处理任务
        InnerEvent innerEvent = InnerEvent.get();
        innerEvent.object = intent;
        mServiceHandler.sendEvent(innerEvent);
    }

    @Override
    protected void onStop() {
        super.onStop();
        //服务销毁，停止子线程
        mServiceEventRunner.stop();
    }

    @Override
    protected IRemoteObject onConnect(Intent intent) {
        return null;
    }

    /**
     * 子类复写，该方法在子线程中回调，在这个方法中处理Intent和耗时操作
     */
    protected abstract void onHandleIntent(Intent intent);

    public ServiceHandler getServiceHandler() {
        return mServiceHandler;
    }

    public EventRunner getServiceEventRunner() {
        return mServiceEventRunner;
    }
}